package com.example.data_receiver.controller;

import com.example.data_receiver.config.TokenConfig;
import com.example.data_receiver.entity.*;
import com.example.data_receiver.service.FinancialService;
import com.example.data_receiver.service.KafkaService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/data/receive/batch")
@RequiredArgsConstructor
@Slf4j
public class DataReceiverController {
    @Autowired
    private FinancialService financialService;

    private final KafkaService kafkaService;

    @Autowired
    private TokenConfig tokenConfig;

    @PostMapping("/{topic}")
    public ResponseEntity<Map<String, Object>> receiveBatchData(
            @PathVariable String topic,
            @RequestBody List<Object> data) {

        log.info("Received batch data request for topic: {}, data size: {}, 接受sap时间:{}", topic, data.size(), LocalDateTime.now());

        Map<String, Object> response = new HashMap<>();
        response.put("status", "success");
        response.put("message", "Data successfully sent to Kafka");
        response.put("topic", topic);
        response.put("count", data.size());

        Long startTime = System.currentTimeMillis();
        try {
            kafkaService.sendBatch(topic, data);

            log.info("Received batch data request for topic: {}, data size: {}, 推送kafka结束时间:{}", topic, data.size(), LocalDateTime.now());
            Long endTime = System.currentTimeMillis();

            response.put("cost", endTime - startTime);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return ResponseEntity.ok(response);
    }

    @PostMapping("/records/yszk")
    public ResponseEntity<String> saveYszkRecords(@RequestBody List<YszkRecord> records) {
        try {
            financialService.saveFinancialRecordsYszk(records);
            return ResponseEntity.ok("数据批量插入yszk成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("数据插入失败: " + e.getMessage());
        }
    }

    @PostMapping("/records/yfzk")
    public ResponseEntity<String> saveYfzkRecords(@RequestBody List<YfzkRecord> records) {
        try {
            financialService.saveFinancialRecordsYfzk(records);

            return ResponseEntity.ok("数据批量插入yfzk成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("数据插入失败: " + e.getMessage());
        }
    }

    @PostMapping("/records/yfzl")
    public ResponseEntity<String> saveYfzlRecords(@RequestBody List<YfzlRecord> records) {
        try {
            financialService.saveFinancialRecordsYfzl(records);

            return ResponseEntity.ok("数据批量插入yfzl成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("数据插入失败: " + e.getMessage());
        }
    }

    @PostMapping("/records/yszl")
    public ResponseEntity<String> saveYszlRecords(@RequestBody List<YszlRecord> records) {
        try {
            financialService.saveFinancialRecordsYszl(records);

            return ResponseEntity.ok("数据批量插入yszl成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("数据插入失败: " + e.getMessage());
        }
    }

    /**
     * 动态获取 token 接口
     *
     * @return 包含 token 的响应实体
     */
    @GetMapping("/getToken")
    public ResponseEntity<Map<String, String>> getToken() {
        Map<String, String> response = new HashMap<>();
        // 使用一个固定的通用用户名生成 token
        String token = tokenConfig.generateToken("generic_user");
        response.put("token", token);
        response.put("status", "success");
        return ResponseEntity.ok(response);
    }

    /**
     * 刷新token接口
     */
    @PostMapping("/refreshToken")
    public ResponseEntity<Map<String, String>> refreshToken(@RequestBody Map<String, String> request) {
        String refreshToken = request.get("refreshToken");
        Map<String, String> response = new HashMap<>();
        if (refreshToken == null) {
            response.put("status", "error");
            response.put("message", "缺少refreshToken");
            return ResponseEntity.badRequest().body(response);
        }
        String username;
        try {
            username = tokenConfig.getUsernameFromToken(refreshToken);
        } catch (Exception e) {
            response.put("status", "error");
            response.put("message", "refreshToken无效");
            return ResponseEntity.status(401).body(response);
        }
        if (tokenConfig.validateRefreshToken(refreshToken, username)) {
            String newAccessToken = tokenConfig.generateToken(username);
            String newRefreshToken = tokenConfig.generateRefreshToken(username);
            response.put("status", "success");
            response.put("accessToken", newAccessToken);
            response.put("refreshToken", newRefreshToken);
            return ResponseEntity.ok(response);
        } else {
            response.put("status", "error");
            response.put("message", "refreshToken校验失败");
            return ResponseEntity.status(401).body(response);
        }
    }
}